<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Support\Facades\Log;
use EasyWeChat\Factory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class AuthController extends Controller
{
    public function wxLogin(Request $request)
    {
        if ($request->input('test') == "696") {
            $user = User::where('id', 2)->first();
            return $this->doLogin($user);
        }
        $app = Factory::officialAccount(config('wechat'));
        $oauth = $app->oauth;
        if ($request->input('code')) {
            $wxUser = $oauth->userFromCode($request->input('code'));
            $user = User::where('openid', $wxUser->getId())->first();
            if (!is_object($user)) {
                $user = new User();
            }
            $user->fill([
                'openid' => $wxUser->getId(),
                'nickname' => $wxUser->getNickname(),
                'avatar' => $this->downloadAvatar($user->id, $wxUser->getAvatar()),
                'gender' => 0,
            ]);
            return $this->doLogin($user);
        } else {
            $redirectUrl = $oauth->withRedirectUrl(env('APP_URL'))->redirect();
            return $this->response($redirectUrl);
        }

//        $openid = $unionid = null;
//        if (!empty($request->input('code'))) {
//            $wxAuth = [];
//            try {
//                $app = Factory::miniProgram(config('wechat'));
//                $wxAuth = $app->auth->session($request->input('code'));
//                $openid = $wxAuth['openid'];
//                $unionid = isset($wxAuth['unionid']) ? $wxAuth['unionid'] : null;
//            } catch (\Exception $e) {
//                Log::error("wx-auth", $wxAuth);
//                abort(5003);
//            }
//        }
//        if (!$user = User::where('open_id', $openid)->first()) {
//            $user = new User();
//        }
//        $params['open_id'] = $openid;
//        $params['union_id'] = $unionid;
//        $params['nickname'] = $request->input('userInfo')['nickName'];
//        $params['avatar'] = $this->downloadAvatar($user->id, $request->input('userInfo')['avatarUrl']);
//        $params['gender'] = $request->input('userInfo')['gender'];
//        return $this->doLogin($user, $params);
    }

    public function doLogin($user, $params = [])
    {
        $user->fill($params);
        if (!$user->save()) {
            abort(5001);
        }
        $token = $user->createToken($user->id);
        return $this->response([
            'token' => $token->plainTextToken,
            'userInfo' => $user
        ]);
    }

    private function downloadAvatar($id, $url)
    {
        $content = file_get_contents($url);
        $path = 'avatar/' . $id . '.png';
        Storage::disk("public")->put($path, $content);
        return Storage::disk("public")->url($path);
    }
}
